package se.topshelf.golftracker.web.controller.player;


import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import se.topshelf.golftracker.core.domain.Country;
import se.topshelf.golftracker.core.domain.GolfId;
import se.topshelf.golftracker.core.domain.MemberClub;
import se.topshelf.golftracker.core.domain.Player;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.core.service.PlayerService;
import se.topshelf.golftracker.web.controller.BaseEntityController;
import se.topshelf.golftracker.web.editor.BaseEntityEditor;

import javax.annotation.Resource;
import java.text.DecimalFormat;

@Controller
@SessionAttributes("entity")
@RequestMapping("/player")
public class PlayerController extends BaseEntityController<Player>{
    static final String ALL_COUNTRIES_MODEL_ATTRIBUTE = "allCountries";
    static final String ENTITY_URL_CONTEXT_PATH = "player";
    static final String ALL_MEMBER_CLUBS_MODEL_ATTRIBUTE = "allMemberClubs";

    @Resource  // Automatically set ("wired") by Spring
    private PlayerService playerService;

    public PlayerController() {
        super(Player.class);
    }

    @Override
    protected String getEntityUrlContextPath() {
        return ENTITY_URL_CONTEXT_PATH;
    }

    @Override
    protected BaseService getBaseService() {
        return playerService;
    }

    @Override
    protected void addModelReferenceData(ModelMap model, Player entity) {
        model.put(ALL_COUNTRIES_MODEL_ATTRIBUTE, super.fetchAllEntitiesAndBuildReferenceDataFor(Country.class));
        model.put(ALL_MEMBER_CLUBS_MODEL_ATTRIBUTE, super.fetchAllEntitiesAndBuildReferenceDataFor(MemberClub.class));

    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, new DecimalFormat("0.##"), true));
        binder.registerCustomEditor(GolfId.class, "golfId", new GolfIdEditor());
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Country.class, "homeAddress.country", new BaseEntityEditor<Country>(Country.class, playerService));
        binder.registerCustomEditor(MemberClub.class, "memberClub", new BaseEntityEditor<MemberClub>(MemberClub.class, playerService));
    }

    @Override
    protected Validator getValidator() {
        return new PlayerValidator(playerService);
    }

    // For tests
    protected void setPlayerService(PlayerService playerService) {
        this.playerService = playerService;
    }
}
